package io.github.generator.util;

import cn.hutool.core.lang.Assert;
import io.github.common.consts.StringPool;
import io.github.common.util.StringUtils;
import io.github.generator.Generator;

import java.net.URL;
import java.nio.file.Paths;
import java.util.StringJoiner;

/**
 * 
 *
 * @author haijun
 * @version 1.0.0
 * @email "mailto:haijun@qq.com"
 * @date 2024.11.09 20:09
 * @since 1.0.0
 */
public class GeneratorUtils {

    /**
     * Gets output dir *
     *
     * @return the output dir
     * @since 1.0.0
     */
    public static String getProjectRoot(String... outputPath) {
        String projectRoot = Paths.get("").toAbsolutePath().toString();
        return Paths.get(projectRoot, outputPath).toString();
    }

    /**
     * Parent path
     *
     * @return the string
     * @since 1.0.0
     */
    public static String getParentPackagePath(Class<?> mainApplicationClass) {
        return mainApplicationClass != null ? mainApplicationClass.getPackage().getName() : getProjectRoot("src", "main", "java");
    }

    /**
     * 获取到包路径
     *
     * @return the package path
     * @since 1.0.0
     */
    public static String getPackagePath(String ...path) {
        StringJoiner joiner = new StringJoiner(StringPool.DOT);
        if (path.length == 0) {
            return StringPool.EMPTY;
        }
        for (String p : path) {
            if (StringUtils.isEmpty(p)) {
                continue;
            }
            joiner.add(p);
        }
        return joiner.toString();
    }

    /**
     * Gets xml file path *
     *
     * @return the xml file path
     * @since 1.0.0
     */
    public static String getXmlFilePath() {
        return Paths.get(getProjectRoot(), "src", "main", "resources", "mapper").toString();
    }

    /**
     * Gets template file path *
     *
     * @param modelName name
     * @return the template file path
     * @since 1.0.0
     */
    public static String getTemplateFilePath(String templatePath, String modelName) {
        ClassLoader classLoader = Generator.class.getClassLoader();
        String path = StringUtils.isNotBlank(templatePath) ? templatePath : "template";
        path = String.format("%s/%s.vm", path, modelName);
        URL resource = classLoader.getResource(path);
        Assert.notNull(resource, "模板文件不存在：" + path);
        return StringUtils.substringBefore(resource.toString(), ".vm");
    }
}
